import axios from 'axios';
import React, { useEffect, useState } from 'react'
import { useParams, useNavigate } from "react-router-dom";
import { Collapse, Tag, Form, Select, Button, Row, Modal, message } from 'antd';

import Play from './Play'
import { API_HOST } from './Util.jsx'

import {
    DeleteOutlined,
    PlusOutlined,
  } from '@ant-design/icons';

function getCurrentUserId() {
    let userInfo = JSON.parse(localStorage.getItem('card_player'))
    return userInfo?.id
}

function getCurrentUserName() {
    let userInfo = JSON.parse(localStorage.getItem('card_player'))
    return userInfo?.username
}


const NewRoundAlert = ({games}) => {

    const [open, setOpen] = useState(false)
    const [title, setTitle] = useState("")
    const [content, setContent] = useState(<></>)
  
    useEffect(() => {
        if (games.length < 2) return

        setTimeout(() => {
            setOpen(false);
        }, 4000);

        let idx = games[1].WinnerIdx
        let content = <>
            <p>{"本轮赢家：" + games[1].Players[idx].Name}</p>
            {
            games[0].State == "GAMEOVER" ?
              <p>游戏已结束</p> :
              <p>即将开始新一轮游戏...</p>
            }
        </>
        setTitle("第"+(games.length-1)+"局已结束")
        setContent(content)
        setOpen(true)
      }, [games?.length])
    
    return (
        <>
        <Modal
            title={title}
            open={open}
            footer={null}
        >
            {content}
        </Modal>
        </>
    );

}

export default function Room() {

  const [messageApi, contextHolder] = message.useMessage();

//   const matches = useMatches();
//   const roomId = matches[0].params?.id

  const {roomId}  = useParams();
  
  const navigate = useNavigate()

  const [view, setView] = useState('unknown')
  const [roomInfo, setRoomInfo] = useState({})

  var interval = null

  useEffect(() => {

    setView('unknown')

    interval = setInterval(() => {

        axios.get(API_HOST()+'/api/room/' + roomId).then((res)=>{

            let room = res.data
            console.log(room)
            setRoomInfo(room)
            if (room.State==="READY") {
                setView('play')
            } else if (room.State==="INIT") {
                setView('setup')
            } else if (room.State==="DISMISSED") {
                setView('finished')
                clearInterval(interval)
            } else {
                setView('unknown')
            }

        }).catch((err)=>{
            console.log(err)
            if( err.response.status===404){
                clearInterval(interval);
                setView('404')
            }
        })
  
      }, 1000);
  
    return () => clearInterval(interval);

  }, []);


  const onAddCandidate = ()=>{
    axios.post(API_HOST()+"/api/room/add_candidate", {"roomId": roomId}).then((res)=>{
        setRoomInfo(res.data)
        messageApi.open({
            type: 'success',
            content: '添加玩家成功',
          });
    }).catch((err)=>{
        console.log(err)
        messageApi.open({
            type: 'error',
            content: '添加玩家失败',
          });
    })
  }

  const onDeleteCandidate = (seatNo)=>{
    axios.post(API_HOST()+"/api/room/delete_candidate", {"roomId": roomId, "seatNo": seatNo}).then((res)=>{
        setRoomInfo(res.data)
        messageApi.open({
            type: 'success',
            content: '删除玩家成功',
          });
    }).catch((err)=>{
        console.log(err)
        messageApi.open({
            type: 'error',
            content: '删除玩家失败',
          });
    })
  }

  const onChangeCandidate = (seatNo, isHuman)=>{
    console.log("onChangeCandidate", roomId, seatNo, isHuman)
    axios.post(API_HOST()+"/api/room/change_candidate", {"roomId": roomId, "seatNo": seatNo, "IsHuman": isHuman}).then((res)=>{
        setRoomInfo(res.data)
        messageApi.open({
            type: 'success',
            content: '修改玩家成功',
          });

    }).catch((err)=>{
        console.log(err)
        messageApi.open({
            type: 'error',
            content: '修改玩家失败',
          });
    })
  }

  const onChangeBotType = (seatNo, BotType)=>{
    console.log("onChangeBotType", roomId, seatNo, BotType)
    axios.post(API_HOST()+"/api/room/change_bot_type", {"roomId": roomId, "seatNo": seatNo, "BotType": BotType}).then((res)=>{
        setRoomInfo(res.data)
        messageApi.open({
            type: 'success',
            content: '修改AI机器人成功',
          });

    }).catch((err)=>{
        console.log(err)
        messageApi.open({
            type: 'error',
            content: '修改AI机器人失败',
          });
    })
  }

  const onCandidateSeated = (seatNo) => {
    axios.post(API_HOST()+"/api/room/candidate_seat", {
        "roomId": roomId,
        "seatNo": seatNo,
        "UserName": getCurrentUserName(),
        "UserId": getCurrentUserId()
    }).then((res)=>{
        setRoomInfo(res.data)
    }).catch((err)=>{
        console.log(err)
        messageApi.open({
            type: 'error',
            content: '占座失败',
          });
    })
  }


  const onCandidateUnseated = (seatNo) => {
    axios.post(API_HOST()+"/api/room/candidate_unseat", {
        "roomId": roomId,
        "seatNo": seatNo,
    }).then((res)=>{
        setRoomInfo(res.data)
    }).catch((err)=>{
        console.log(err)
        messageApi.open({
            type: 'error',
            content: '离座失败',
          });
    })
  }

  const onStartPlay = () => {
    axios.post(API_HOST()+"/api/room/" + roomId +"/ready").then((res)=>{
        console.log(res.data)

        setRoomInfo(res.data)
        clearInterval(interval);
        setView('play')
    }).catch((err)=>{
        console.log(err)
        messageApi.open({
            type: 'error',
            content: '开始游戏失败',
          });
    })

  }

  const isSeated = () =>{
    let id = getCurrentUserId()
    return roomInfo?.Candidates?.some((x) => x.Id == id)
  }

  const isTeamReady = () => {

    if (!roomInfo.Candidates) return false
    
    let ready = true
    for (var p of roomInfo.Candidates) {
        if (p.IsHuman && p.Id == ""){
            ready = false
            break
        }
    }
    return ready
}



  return (

    <>
    {contextHolder}

    <div><h1>Room: {roomId}</h1></div>

    {
    (()=>{
    switch(view)
        {
        case '404':
            return <div>房间不存在！ <Button onClick={()=>navigate("/")}>返回大厅</Button></div>

        case 'setup':
            return (
            <div>
                <p>正在组队，倒计时 {roomInfo?.TTL}</p>
                {
                    roomInfo.OwnerId === getCurrentUserId() ? 

                    <div>
                    <Button type="primary" disabled={!isTeamReady()} onClick={onStartPlay}>开始游戏</Button>

                    { roomInfo?.Candidates?.map((x, idx)=> {
                        // {console.log(x)}
                        return <Row key={idx}>
                            <Form layout='inline'
                            >
                                <div style={{"width": "100px"}}>
                                    玩家{idx +1 }
                                    {
                                    // 至少需要2个玩家。因此，不能删除玩家1-3
                                    idx>=3 && 
                                    <Button type='link' onClick={()=>{onDeleteCandidate(idx)}} icon={<DeleteOutlined />} />
                                    }
                                </div>

                                <Form.Item>
                                    <Select
                                        options={[{value: false,label: 'AI',},{value: true,label: 'Human',}]}
                                        defaultValue={x.IsHuman}
                                        onChange={(param)=>onChangeCandidate(idx, param)}
                                    >
                                    </Select>
                                </Form.Item>

                                {
                                    x.IsHuman || <Form.Item>
                                        <Select
                                            options={[{value: 0,label: '规则',},{value: 1,label: '模型1',}]}
                                            defaultValue={x.BotType}
                                            onChange={(param)=>onChangeBotType(idx, param)}
                                        >
                                        </Select>
                                    </Form.Item>
                                }

                                {
                                    // 显示占据当前座位的用户名
                                    x.IsHuman && <span style={{"width": "100px"}}>{x.Name}</span>
                                }

                                {
                                    // 就座按钮：如果该座位没有人占座(x.Name='')，并且自己（当前用户）没有占任何座
                                    
                                    x.IsHuman && x.Id=='' && !isSeated() && <Button onClick={()=>{onCandidateSeated(idx)}}>就座</Button>
                                }

                                {
                                    // 离座按钮：如果当前座位 x.Name== 当前用户
                                    x.Id == getCurrentUserId() && <Button onClick={()=>{onCandidateUnseated(idx)}}>离座</Button>
                                }

                            </Form>
                        </Row>
                    }) }
                    
                    <Row>
                        <Button type='dashed' onClick={onAddCandidate} icon={<PlusOutlined />} />
                    </Row>

                    </div> : <div>
                        
                        { isTeamReady() ? "组队完成，等待房主开始游戏" : "等待玩家加入" }
                        { roomInfo?.Candidates?.map((x, idx)=> {
                        // {console.log(x)}
                        return <Row key={idx}>
                            <div
                            >
                                <span style={{"width": "100px"}}>
                                    玩家{idx +1 }
                                </span>

                                <span style={{"width": "100px"}}>
                                        {
                                            x.IsHuman ? 
                                            (
                                                x.Id === "" ? "等待加入" : x.Name
                                            )
                                            : "AI"
                                        }
                                </span>

                                {
                                    // 就座按钮：如果该座位没有人占座(x.Id='')，并且自己（当前用户）没有占任何座
                                    
                                    x.IsHuman && x.Id=='' && !isSeated() && <Button onClick={()=>{onCandidateSeated(idx)}}>就座</Button>
                                }

                                {
                                    // 离座按钮：如果当前座位 x.Id== 当前用户
                                    x.Id == getCurrentUserId() && <Button onClick={()=>{onCandidateUnseated(idx)}}>离座</Button>
                                }

                            </div>
                        </Row>
                    }) }                            
                    </div>
                }
            </div>
            )

            case 'finished':
            case 'play':
                return <div>
                    { view==='finished' && <Tag color="#f50">已解散</Tag> }
                    { view==='play'     && <Tag color="#5f0">游戏中</Tag> }

                    <Collapse 
                    defaultActiveKey={[0]}
                    items={
                        roomInfo.Games.map((game, idx)=>{
                            let N = roomInfo.Games.length
                            return {
                                key: idx,
                                label: '第'+ (N-idx) +'局，在玩人数' + game.NumWinners + '，胜者：' + game.WinnerIdx,
                                children: <Play game={game}/>
                            }
                        })
                    }
                    >
                    </Collapse>
                    <NewRoundAlert games={roomInfo.Games}/>
                </div>

        case 'unknown':
        default:
            return <div>正在加载...</div>

        }

        })()
    }

    </>
  )
}
